<template>
  <div class="four">
    
    <div class="chart-wrapper">
      
      <!-- <div id="barChart" class="chart-container"></div> -->
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
import * as echarts from "echarts";

let arr_color = ['#177F0D','#7D1B5E','#588E79','#8F6C4D','#09B4E7','#65E72E','#16A298','#92302A'];
// 定义响应式数据
const option = ref({
  title: {
    left: "left",
    // text: "柱状图示例",
    // top: "10%",
    textStyle: {
      color: "#fff"
    }
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    },
    formatter: '{b}: {c}',
    textStyle: {
      color: "#000"
    }
  },
  grid: {
    left: "3%",
    right: "4%",
    bottom: "5%",
    // top: "30%",
    containLabel: true
  },
  xAxis: {
    type: "category",
    data: [],
    axisLabel: {
      fontSize: 14,
      color: "#fff"
    }
  },
  yAxis: {
    type: "value",
    axisLabel: {
      formatter: '{value}',
      color: "#fff"
    }
  },
  series: [
    {
      name: "数据",
      type: "bar",
      barWidth: "60%",
      itemStyle: {
        borderRadius: [10, 10, 0, 0]
      },
      label: {
        show: true,
        position: 'top',
        formatter: '{c}',
        textStyle: {
          color: "#fff"
        }
      },
      data: [],
    },
  ],
});

// 声明myChart变量以便在函数间共享
let myChart;
// 生成随机颜色的函数
const getRandomColor = () => {
  const letters = '0123456789ABCDEF';
  let color = '#';
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  arr_color.push(color);
  console.log(arr_color.toString())
  // console.log(color);
  return color;
};

// 更新图表数据的函数
const updateChartData = (title, data) => {
  // var index = 0;
  option.value.xAxis.data = title;
  // 为每个数据项添加随机颜色
  const dataWithRandomColors = data.map((value, index) => ({
    value: value,
    itemStyle: {
      color:  arr_color[index]
    }
  }));
  option.value.series[0].data = dataWithRandomColors;
  if (myChart) {
    myChart.setOption(option.value);
  }
};

// 暴露方法给父组件
defineExpose({
  updateChartData
});

onMounted(() => {
  // 初始化图表
  const chartDom = document.getElementById("barChart");
  myChart = echarts.init(chartDom);

  // 应用配置
  myChart.setOption(option.value);

  // 监听窗口大小变化，调整图表尺寸
  window.addEventListener("resize", () => {
    myChart.resize();
  });
});
</script>

<style lang='scss' scoped>
.four {
  width: 100%;
  height: 100%;
}

.chart-wrapper {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  height: 100%;
}

.chart-container {
  width: 100%;
  height: 100%;
}
</style>
